package com.lzh.chatnote.user.service.impl;

import com.lzh.chatnote.common.antation.RedisLock;
import com.lzh.chatnote.common.mqConsumer.IdempotentEnum;
import com.lzh.chatnote.user.dao.ItemConfigDao;
import com.lzh.chatnote.user.dao.UserBackpackDao;
import com.lzh.chatnote.user.domain.entity.UserBackpack;
import com.lzh.chatnote.user.domain.enums.ItemTypeEnum;
import com.lzh.chatnote.user.domain.enums.YesOrNoEnum;
import com.lzh.chatnote.user.service.UserBackpackService;
import com.lzh.chatnote.user.service.cache.ItemCache;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;


@Service
public class UserBackpackServiceImpl implements UserBackpackService {
    @Resource
    private UserBackpackDao userBackpackDao;
    @Resource
    private ItemCache itemCache;
    @Resource
    private ItemConfigDao itemConfigDao;
    @Resource
    @Lazy
    private UserBackpackServiceImpl userBackpackServiceImpl;


    @Override
    public void acquireItem(Long uuid, Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        //获取幂等号
        String  uniqueNo  =  tryAcquireItemNO(itemId, idempotentEnum, businessId);
        //发放改名卡
        userBackpackServiceImpl.doAcquireItem(uuid, itemId, uniqueNo);
    }


    @RedisLock(key = "#uniqueNo")
    public  void doAcquireItem(Long uuid, Long itemId, String uniqueNo) {
        UserBackpack userBackpack  =  userBackpackDao.existAcquireItem(uuid, itemId);
        //校验幂等号是否存在
        if(Objects.nonNull(userBackpack)){
            return ;
        }

        //校验业务徽章获得只能获得一次todo
        userBackpack = UserBackpack.builder()
                .uid(uuid)
                .itemId(itemId)
                .itemType(ItemTypeEnum.ITEM.getType().toString())
                .status(YesOrNoEnum.YES.getType())
                .idempotent(uniqueNo)
                .build();
        userBackpackDao.save(userBackpack);
    }



    private String tryAcquireItemNO(Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        return  String.format("%s_%s_%s",  itemId,idempotentEnum.getType(), businessId);
    }
}
